package com.study.Controller;

import com.common.Entity.Result;
import com.common.Utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import com.study.Entity.Article;
import com.study.Service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/getArticleList")
    public Result getAllArticle(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(required = false) String categoryId,
                                @RequestParam(required = false) String title,
                                @RequestParam(required = false) String status,
                                @RequestParam(required = false) String token){
        if (!Objects.equals(token, "")) {
            String username = JwtUtil.extractUsername(token);
            if (username == null) {
                return Result.error("无效的token");
            }
            PageInfo<Article> pageInfo = articleService.getArticleListByThree(pageNum, pageSize, categoryId, title,status,username);
            return Result.success(pageInfo);
        }
        PageInfo<Article> pageInfo = articleService.getArticleList(pageNum, pageSize, categoryId, title,status);
        return Result.success(pageInfo);
    }

    @PostMapping("/addArticle")
    public Result addArticle(@RequestBody Article article) {
        articleService.addArticle(article);
        return Result.success();
    }

    @PutMapping("/updateArticle")
    public Result updateArticle(@RequestBody Article article) {
        articleService.updateArticle(article);
        return Result.success();
    }

    @DeleteMapping("/deleteArticle/{articleId}")
    public Result deleteArticle(@PathVariable("articleId") String articleId) {
        articleService.deleteArticle(articleId);
        return Result.success();
    }

    @PutMapping("/updateArticleStatus")
    public Result updateArticleStatus(@RequestBody Article article) {
        articleService.updateArticle(article);
        return Result.success();
    }
}
